import akshare as ak
import pandas as pd
import numpy as np

# 获取股票日线数据
def get_stock_data(code, start_date, end_date):
    try:
        data = ak.stock_zh_a_hist(symbol=code, period="daily", start_date=start_date, end_date=end_date)
        data.rename(columns={'日期': 'date', '开盘': 'open', '收盘': 'close', '最高': 'high', '最低': 'low', '成交量': 'volume'}, inplace=True)
        data.index = pd.to_datetime(data['date'])
        return data
    except Exception as e:
        print(f"Error fetching data for {code}: {e}")
        return None

# 分析热门板块（通过板块涨幅排名选择涨幅大的板块）
def analyze_hot_sectors():
    sector_performance = ak.stock_sector_spot()
    hot_sectors = sector_performance.nlargest(5, '涨跌幅')['板块'].tolist()  # 取涨幅排名前5的板块
    return hot_sectors

# 初步筛选股票（基于热门板块、涨幅和成交量条件）
def preliminary_screen_stocks(hot_sectors, all_stocks_data):
    screened_stocks = []
    for _, row in all_stocks_data.iterrows():
        code = row['代码']
        stock_data = get_stock_data(code, start_date='2024-01-01', end_date='2024-10-27')
        if stock_data is not None and len(stock_data) > 0:
            recent_gain = (stock_data['close'][-1] - stock_data['close'][-3]) / stock_data['close'][-3] * 100
            average_volume = stock_data['volume'].rolling(window=10).mean()
            current_volume = stock_data['volume'][-1]
            if (row['板块'] in hot_sectors) and (recent_gain > 15) and (current_volume > 2 * average_volume[-1]):
                screened_stocks.append(code)
    return screened_stocks

# 技术分析（K线形态、均线、成交量综合判断）
def technical_analysis(code):
    data = get_stock_data(code, start_date='2024-01-01', end_date='2024-10-27')
    if data is None or len(data) < 10:
        return False
    # K线形态判断（简单示例：类似红三兵形态）
    kline_condition = ((data['close'][-3] < data['open'][-3]) and (data['close'][-2] > data['open'][-2]) and (data['close'][-1] > data['open'][-1]))
    # 均线系统判断（5日均线金叉10日均线）
    ma5 = data['close'].rolling(window=5).mean()
    ma10 = data['close'].rolling(window=10).mean()
    ma_condition = (ma5[-1] > ma10[-1]) and (ma5[-2] <= ma10[-2])
    # 成交量分析（当前成交量大于5日平均成交量）
    volume_condition = data['volume'][-1] > data['volume'].rolling(window=5).mean()[-1]
    return kline_condition and ma_condition and volume_condition

# 盘口观察（这里简单模拟集合竞价和早盘情况，假设数据中有集合竞价价格信息）
def pre_market_observation(code):
    try:
        spot_data = ak.stock_zh_a_spot_em()
        if code in spot_data['代码'].values:
            stock_info = spot_data[spot_data['代码'] == code]
            open_auction_gap = (stock_info['今开'].values[0] - stock_info['昨收'].values[0]) / stock_info['昨收'].values[0] * 100
            return open_auction_gap > 3
        return False
    except Exception as e:
        print(f"Error in pre - market observation for {code}: {e}")
        return False

# 综合交易策略
def trading_strategy():
    all_stocks_data = ak.stock_info_a_code_name()
    hot_sectors = analyze_hot_sectors()
    screened_stocks = preliminary_screen_stocks(hot_sectors, all_stocks_data)
    potential_stocks = []
    for stock in screened_stocks:
        if technical_analysis(stock) and pre_market_observation(stock):
            potential_stocks.append(stock)
    return potential_stocks

# 主函数，运行交易策略
if __name__ == "__main__":
    potential_stocks = trading_strategy()
    print("Potential stocks with high - rise potential:", potential_stocks)